package com.lei.springbootpractice.controller;

import com.lei.springbootpractice.pojo.CategoryPojo;
import com.lei.springbootpractice.pojo.ProductsPojo;
import com.lei.springbootpractice.pojo.OrdersPojo;
import com.lei.springbootpractice.pojo.UserPojo;
import com.lei.springbootpractice.service.*;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/admin")
public class AdminController {

    private final UserService userService;
    private final ProductsService productsService;
    private final CategoryService categoryService;
    private final ImageService imageService;
    private final OrdersService ordersService;

    @Autowired
    public AdminController(UserService userService, ProductsService productsService,
                          CategoryService categoryService, ImageService imageService,
                          OrdersService ordersService) {
        this.userService = userService;
        this.productsService = productsService;
        this.categoryService = categoryService;
        this.imageService = imageService;
        this.ordersService = ordersService;
    }

    // 助手方法：为管理员页面添加通用属性
    private void addAdminAttributes(Model model, HttpSession session) {
        // 获取当前登录用户信息
        String userID = (String) session.getAttribute("loggedInUser");
        UserPojo user = userService.getUserByUserID(userID);
        
        model.addAttribute("userRole", user.getRole());
        model.addAttribute("username", user.getUserName());
        
        // 为了兼容性，保留isAdmin属性
        model.addAttribute("isAdmin", true);
    }
    
    // 重载方法：当没有session时使用默认值
    private void addAdminAttributes(Model model) {
        model.addAttribute("userRole", "admin");
        model.addAttribute("isAdmin", true);
    }

    @GetMapping("/users")
    public String userManagement(Model model) {
        List<UserPojo> users = userService.getAllUsers();
        model.addAttribute("users", users != null ? users : new ArrayList<>());
        addAdminAttributes(model);
        return "admin/user-list";
    }

    @GetMapping("/users/delete/{id}")
    public String deleteUser(@PathVariable("id") String userId) {
        // 添加日志输出
        System.out.println("正在删除用户：" + userId);
        userService.deleteUser(userId);
        return "redirect:/admin/users";
    }
    @GetMapping("/dashboard")
    public String dashboard(HttpSession session, Model model) {
        String userID = (String) session.getAttribute("loggedInUser");
        UserPojo user = userService.getUserByUserID(userID);

        // 进入管理员工作台时刷新分类缓存
        categoryService.clearCache();
        categoryService.warmUpCache();

        // 添加用户总数统计
        int userCount = userService.getAllUsers().size();

        model.addAttribute("username", user.getUserName());
        model.addAttribute("userCount", userCount);  // 新增统计值
        addAdminAttributes(model, session);
        return "admin/dashboard";
    }

    @GetMapping("/users/changeRole/{id}")
    public String showChangeRoleForm(@PathVariable("id") String userID, Model model) {
        UserPojo user = userService.getUserByUserID(userID);
        model.addAttribute("user", user);
        addAdminAttributes(model);
        return "admin/change-role";
    }

    @PostMapping("/users/changeRole")
    public String changeRole(@RequestParam("userID") String userID,
                           @RequestParam("role") String newRole,
                           HttpSession session,
                           Model model) {
        // 获取当前操作用户
        String currentUserID = (String) session.getAttribute("loggedInUser");
        UserPojo currentUser = userService.getUserByUserID(currentUserID);
        UserPojo targetUser = userService.getUserByUserID(userID);

        // 安全检查：不能修改自己的角色
        if(currentUserID.equals(userID)) {
            model.addAttribute("error", "不能修改自己的角色");
            return "redirect:/admin/users";
        }

        // 安全检查：超级管理员不能被其他人修改
        if("super_admin".equals(targetUser.getRole()) && !"super_admin".equals(currentUser.getRole())) {
            model.addAttribute("error", "无权修改超级管理员");
            return "redirect:/admin/users";
        }

        // 安全检查：不能设置超级管理员角色
        if("super_admin".equals(newRole) && !"super_admin".equals(currentUser.getRole())) {
            model.addAttribute("error", "无权设置超级管理员角色");
            return "redirect:/admin/users";
        }

        if(targetUser != null) {
            // 只有超级管理员可以修改其他管理员
            if(("admin".equals(targetUser.getRole()) || "admin".equals(newRole))
                && !"super_admin".equals(currentUser.getRole())) {
                model.addAttribute("error", "无权修改管理员角色");
                return "redirect:/admin/users";
            }

            // 普通管理员只能修改客服和客户
            if("admin".equals(currentUser.getRole()) &&
               !List.of("customer_service", "customer").contains(targetUser.getRole())) {
                model.addAttribute("error", "无权修改该用户角色");
                return "redirect:/admin/users";
            }

            System.out.println("用户[" + currentUserID + "]将用户[" + userID +
                             "]的角色从" + targetUser.getRole() + "修改为" + newRole);
            targetUser.setRole(newRole);
            userService.updateUser(targetUser);
        }

        return "redirect:/admin/users";
    }

    @GetMapping("/products/add")
    public String showAddProductForm(Model model) {
        // 获取所有父分类
        List<CategoryPojo> parentCategories = categoryService.getParentCategories();

        // 为每个父分类获取其子分类
        Map<String, List<CategoryPojo>> subCategoriesMap = new HashMap<>();
        for (CategoryPojo parent : parentCategories) {
            List<CategoryPojo> subCategories = categoryService.getSubcategories(parent.getCategoryId());
            subCategoriesMap.put(parent.getCategoryId(), subCategories);
        }

        model.addAttribute("product", new ProductsPojo());
        model.addAttribute("parentCategories", parentCategories);
        model.addAttribute("subCategoriesMap", subCategoriesMap);
        addAdminAttributes(model);

        return "admin/product-form";
    }

    @GetMapping("/products")
    public String productManagement(
            @RequestParam(required = false) String categoryId,
            @RequestParam(required = false) String parentCategoryId,
            @RequestParam(required = false) Double minPrice,
            @RequestParam(required = false) Double maxPrice,
            Model model) {

        // 获取所有父分类
        List<CategoryPojo> parentCategories = categoryService.getParentCategories();
        model.addAttribute("parentCategories", parentCategories);

        // 构建子分类映射
        Map<String, List<CategoryPojo>> subCategoriesMap = new HashMap<>();
        for (CategoryPojo parent : parentCategories) {
            List<CategoryPojo> subCategories = categoryService.getSubcategories(parent.getCategoryId());
            subCategoriesMap.put(parent.getCategoryId(), subCategories);
        }
        model.addAttribute("subCategoriesMap", subCategoriesMap);

        // 构建筛选条件
        List<String> categoryIds = new ArrayList<>();
        if (categoryId != null && !categoryId.isEmpty()) {
            categoryIds.add(categoryId);
        } else if (parentCategoryId != null && !parentCategoryId.isEmpty()) {
            // 如果只选择了父分类，获取该父分类下的所有子分类
            List<CategoryPojo> subCategories = categoryService.getSubcategories(parentCategoryId);
            for (CategoryPojo sub : subCategories) {
                categoryIds.add(sub.getCategoryId());
            }
        }

        // 获取筛选后的商品
        List<ProductsPojo> products = productsService.getProductsByFilter(categoryIds, minPrice, maxPrice);
        model.addAttribute("products", products);
        addAdminAttributes(model);

        return "admin/product-list";
    }

    @GetMapping("/products/edit/{id}")
    public String showEditProductForm(@PathVariable("id") String productId, Model model) {
        ProductsPojo product = productsService.getProductById(productId);
        List<CategoryPojo> parentCategories = categoryService.getParentCategories();
        Map<String, List<CategoryPojo>> subCategoriesMap = new HashMap<>();
        for (CategoryPojo parent : parentCategories) {
            subCategoriesMap.put(parent.getCategoryId(), categoryService.getSubcategories(parent.getCategoryId()));
        }

        model.addAttribute("product", product);
        model.addAttribute("parentCategories", parentCategories);
        model.addAttribute("subCategoriesMap", subCategoriesMap);
        addAdminAttributes(model);
        return "admin/product-form";
    }

    @PostMapping("/products/update")
    public String updateProduct(@ModelAttribute ProductsPojo product,
                              @RequestParam(value = "productImage", required = false) MultipartFile productImage,
                              Model model) {
        try {
            // 如果上传了新图片，转换为Base64格式
            if (productImage != null && !productImage.isEmpty()) {
                String base64Image = imageService.convertImageToBase64(productImage);
                product.setPhoto(base64Image);
                System.out.println("商品图片已更新为Base64格式，大小：" + base64Image.length() + " 字符");
            }
            // 如果没有上传新图片，保持原有图片不变

            productsService.updateProduct(product);
            return "redirect:/admin/products";
        } catch (IOException e) {
            System.err.println("图片处理失败：" + e.getMessage());
            model.addAttribute("error", "图片处理失败：" + e.getMessage());

            // 重新加载表单数据
            List<CategoryPojo> parentCategories = categoryService.getParentCategories();
            Map<String, List<CategoryPojo>> subCategoriesMap = new HashMap<>();
            for (CategoryPojo parent : parentCategories) {
                subCategoriesMap.put(parent.getCategoryId(), categoryService.getSubcategories(parent.getCategoryId()));
            }

            model.addAttribute("product", product);
            model.addAttribute("parentCategories", parentCategories);
            model.addAttribute("subCategoriesMap", subCategoriesMap);
            addAdminAttributes(model);
            return "admin/product-form";
        }
    }

    @GetMapping("/products/delete/{id}")
    public String deleteProduct(@PathVariable("id") String productId) {
        // 使用Base64存储后，删除商品时不需要删除文件系统中的图片文件
        productsService.deleteProduct(productId);
        return "redirect:/admin/products";
    }

    @PostMapping("/products/add")
    public String addProduct(@ModelAttribute ProductsPojo product,
                           @RequestParam("productImage") MultipartFile productImage,
                           Model model) {
        try {
            // 验证图片是否上传
            if (productImage == null || productImage.isEmpty()) {
                model.addAttribute("error", "请选择商品图片");

                // 重新加载表单数据
                List<CategoryPojo> parentCategories = categoryService.getParentCategories();
                Map<String, List<CategoryPojo>> subCategoriesMap = new HashMap<>();
                for (CategoryPojo parent : parentCategories) {
                    subCategoriesMap.put(parent.getCategoryId(), categoryService.getSubcategories(parent.getCategoryId()));
                }

                model.addAttribute("product", product);
                model.addAttribute("parentCategories", parentCategories);
                model.addAttribute("subCategoriesMap", subCategoriesMap);
                addAdminAttributes(model);
                return "admin/product-form";
            }

            // 将图片转换为Base64格式
            String base64Image = imageService.convertImageToBase64(productImage);
            product.setPhoto(base64Image);

            System.out.println("商品图片已转换为Base64格式，大小：" + base64Image.length() + " 字符");

            product.setProductId(UUID.randomUUID().toString());
            productsService.addProduct(product);
            return "redirect:/admin/products";
        } catch (IOException e) {
            System.err.println("图片处理失败：" + e.getMessage());
            model.addAttribute("error", "图片处理失败：" + e.getMessage());

            // 重新加载表单数据
            List<CategoryPojo> parentCategories = categoryService.getParentCategories();
            Map<String, List<CategoryPojo>> subCategoriesMap = new HashMap<>();
            for (CategoryPojo parent : parentCategories) {
                subCategoriesMap.put(parent.getCategoryId(), categoryService.getSubcategories(parent.getCategoryId()));
            }

            model.addAttribute("product", product);
            model.addAttribute("parentCategories", parentCategories);
            model.addAttribute("subCategoriesMap", subCategoriesMap);
            addAdminAttributes(model);
            return "admin/product-form";
        }
    }

    // 分类管理相关方法
    @GetMapping("/categories")
    public String categoryManagement(Model model) {
        // 强制刷新缓存
        categoryService.clearCache();
        categoryService.warmUpCache();

        List<CategoryPojo> parentCategories = categoryService.getParentCategories();

        // 为每个父分类获取其子分类
        Map<String, List<CategoryPojo>> subCategoriesMap = new HashMap<>();
        for (CategoryPojo parent : parentCategories) {
            List<CategoryPojo> subCategories = categoryService.getSubcategories(parent.getCategoryId());
            subCategoriesMap.put(parent.getCategoryId(), subCategories);
        }

        model.addAttribute("parentCategories", parentCategories);
        model.addAttribute("subCategoriesMap", subCategoriesMap);
        addAdminAttributes(model);

        return "admin/category-list";
    }

    @GetMapping("/categories/add")
    public String showAddCategoryForm(Model model) {
        CategoryPojo category = new CategoryPojo();
        List<CategoryPojo> parentCategories = categoryService.getParentCategories();

        model.addAttribute("category", category);
        model.addAttribute("parentCategories", parentCategories);
        addAdminAttributes(model);

        return "admin/category-form";
    }

    @PostMapping("/categories/add")
    public String addCategory(@ModelAttribute CategoryPojo category, 
                            @RequestParam("categoryType") String categoryType,
                            Model model) {

        // 验证输入
        if (category.getCategoryName() == null || category.getCategoryName().trim().isEmpty()) {
            model.addAttribute("error", "分类名称不能为空");
            model.addAttribute("category", category);
            model.addAttribute("parentCategories", categoryService.getParentCategories());
            addAdminAttributes(model);
            return "admin/category-form";
        }

        // 根据分类类型设置父分类ID
        if ("parent".equals(categoryType)) {
            category.setParentCategoryId(null); // 父分类的parentCategoryId为null
        } else if ("sub".equals(categoryType)) {
            // 验证子分类必须有父分类
            if (category.getParentCategoryId() == null || category.getParentCategoryId().trim().isEmpty()) {
                model.addAttribute("error", "子分类必须选择一个父分类");
                model.addAttribute("category", category);
                model.addAttribute("parentCategories", categoryService.getParentCategories());
                addAdminAttributes(model);
                return "admin/category-form";
            }

            // 验证父分类是否存在
            CategoryPojo parentCategory = categoryService.getCategoryById(category.getParentCategoryId());
            if (parentCategory == null) {
                model.addAttribute("error", "所选择的父分类不存在");
                model.addAttribute("category", category);
                model.addAttribute("parentCategories", categoryService.getParentCategories());
                addAdminAttributes(model);
                return "admin/category-form";
            }

            // 验证父分类不能是子分类
            if (parentCategory.getParentCategoryId() != null) {
                model.addAttribute("error", "所选择的分类不是有效的父分类");
                model.addAttribute("category", category);
                model.addAttribute("parentCategories", categoryService.getParentCategories());
                addAdminAttributes(model);
                return "admin/category-form";
            }
        }

        // 生成分类ID
        category.setCategoryId(UUID.randomUUID().toString());

        System.out.println("添加分类：" + category.getCategoryName() + 
                          ", 父分类ID：" + category.getParentCategoryId() +
                          ", 是否为父分类：" + (category.getParentCategoryId() == null));

        categoryService.addCategory(category);
        return "redirect:/admin/categories";
    }

    @GetMapping("/categories/edit/{id}")
    public String showEditCategoryForm(@PathVariable("id") String categoryId, Model model) {
        CategoryPojo category = categoryService.getCategoryById(categoryId);
        List<CategoryPojo> parentCategories = categoryService.getParentCategories();

        // 如果编辑的是父分类，从列表中移除自己，避免循环引用
        if (category.getParentCategoryId() == null) {
            parentCategories.removeIf(p -> p.getCategoryId().equals(categoryId));
        }

        model.addAttribute("category", category);
        model.addAttribute("parentCategories", parentCategories);
        addAdminAttributes(model);

        return "admin/category-form";
    }

    @PostMapping("/categories/update")
    public String updateCategory(@ModelAttribute CategoryPojo category,
                               @RequestParam("categoryType") String categoryType,
                               Model model) {

        // 验证输入
        if (category.getCategoryName() == null || category.getCategoryName().trim().isEmpty()) {
            model.addAttribute("error", "分类名称不能为空");
            model.addAttribute("category", category);
            model.addAttribute("parentCategories", categoryService.getParentCategories());
            addAdminAttributes(model);
            return "admin/category-form";
        }

        // 根据分类类型设置父分类ID
        if ("parent".equals(categoryType)) {
            category.setParentCategoryId(null);
        } else if ("sub".equals(categoryType)) {
            // 验证子分类必须有父分类
            if (category.getParentCategoryId() == null || category.getParentCategoryId().trim().isEmpty()) {
                model.addAttribute("error", "子分类必须选择一个父分类");
                model.addAttribute("category", category);
                model.addAttribute("parentCategories", categoryService.getParentCategories());
                addAdminAttributes(model);
                return "admin/category-form";
            }

            // 验证不能将分类设置为自己的子分类
            if (category.getCategoryId().equals(category.getParentCategoryId())) {
                model.addAttribute("error", "不能将分类设置为自己的子分类");
                model.addAttribute("category", category);
                model.addAttribute("parentCategories", categoryService.getParentCategories());
                addAdminAttributes(model);
                return "admin/category-form";
            }

            // 验证父分类是否存在
            CategoryPojo parentCategory = categoryService.getCategoryById(category.getParentCategoryId());
            if (parentCategory == null) {
                model.addAttribute("error", "所选择的父分类不存在");
                model.addAttribute("category", category);
                model.addAttribute("parentCategories", categoryService.getParentCategories());
                addAdminAttributes(model);
                return "admin/category-form";
            }
        }

        System.out.println("更新分类：" + category.getCategoryName() + 
                          ", 父分类ID：" + category.getParentCategoryId() +
                          ", 是否为父分类：" + (category.getParentCategoryId() == null));

        categoryService.updateCategory(category);
        return "redirect:/admin/categories";
    }

    @GetMapping("/categories/delete/{id}")
    public String deleteCategory(@PathVariable("id") String categoryId) {
        // 检查是否有商品使用此分类
        List<ProductsPojo> products = productsService.getProductsByCategory(categoryId);
        if (!products.isEmpty()) {
            // 如果有商品使用此分类，不允许删除
            return "redirect:/admin/categories?error=categoryInUse";
        }

        // 检查是否有子分类
        List<CategoryPojo> subCategories = categoryService.getSubcategories(categoryId);
        if (!subCategories.isEmpty()) {
            // 如果有子分类，不允许删除
            return "redirect:/admin/categories?error=hasSubCategories";
        }

        categoryService.deleteCategory(categoryId);
        return "redirect:/admin/categories";
    }

    @GetMapping("/orders")
    public String orderManagement(
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            Model model) {
        List<OrdersPojo> orders = ordersService.getAllOrders(status, startDate, endDate);
        model.addAttribute("orders", orders);
        model.addAttribute("status", status);
        model.addAttribute("startDate", startDate);
        model.addAttribute("endDate", endDate);
        addAdminAttributes(model);
        return "admin/orders";
    }

    @GetMapping("/orders/detail/{id}")
    public String orderDetail(@PathVariable String id, Model model) {
        OrdersPojo order = ordersService.getOrderDetail(id);
        model.addAttribute("order", order);
        addAdminAttributes(model);
        return "admin/order-detail";
    }

    @PostMapping("/orders/update-status")
    public String updateOrderStatus(
            @RequestParam String orderId,
            @RequestParam String status,
            @RequestParam(required = false) String shippingCompany,
            @RequestParam(required = false) String shippingNo,
            Model model) {

        boolean result = ordersService.updateOrderStatus(orderId, status, shippingCompany, shippingNo);
        if (result) {
            model.addAttribute("message", "订单状态更新成功");
        } else {
            model.addAttribute("error", "订单状态更新失败");
        }
        return "redirect:/admin/orders/detail/" + orderId;
    }
}